package cn.pugle.base.thread.ticketlock;

/**
 * @author tzp
 */
@SuppressWarnings("Duplicates")
public class TicketLockTest2 {
    public static void main(String[] args) throws InterruptedException {
        TicketLock5 ticketLock = new TicketLock5();

        MyTask myTask1 = new MyTask(1L, ticketLock);
        new Thread(myTask1).start();

        Thread.sleep(10);

        MyTask myTask2 = new MyTask(2L, ticketLock);
        Thread thread2 = new Thread(myTask2);
        thread2.start();

        thread2.join();
        System.out.println(ticketLock);
        System.out.println(ticketLock.getLock(1L));
        System.out.println(ticketLock);
    }


    static class MyTask implements Runnable {

        Long idToLock;
        TicketLock5 ticketLock;

        public MyTask(Long idToLock, TicketLock5 ticketLock) {
            this.idToLock = idToLock;
            this.ticketLock = ticketLock;
        }

        @Override
        public void run() {
            Object lock = ticketLock.getLock(idToLock);
            synchronized (lock) {
                System.out.println(Thread.currentThread() + " get lock " + idToLock + ": " + lock);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + " quit lock area");
            }
        }
    }

}
